package main

import (
	"log"
	"os"
	"time"

	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/app/server/registry"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"github.com/hertz-contrib/registry/eureka"
	"github.com/joho/godotenv"
)

func main() {
	// 加载环境变量
	err := godotenv.Load(".env")
	if err != nil {
		panic("Error loading .env file: " + err.Error())
	}

	// 设置默认环境变量
	env := os.Getenv("ENV")
	if env == "" {
		env = "prod"
	}

	// 初始化 AI Agent
	openAIAPIKey := os.Getenv("API_KEY")
	if openAIAPIKey == "" {
		log.Panic("API_KEY is not set in .env file")
	}

	modelName := os.Getenv("MODEL")
	if modelName == "" {
		log.Panic("MODEL is not set in .env file")
	}

	baseUrl := os.Getenv("BASE_URL")
	if baseUrl == "" {
		baseUrl = "https://api.openai.com/v1"
	}

	// 初始化服务
	addr := os.Getenv("SERVICE_ADDR")
	if addr == "" {
		addr = "127.0.0.1:8888"
	}

	eurekaUrl := os.Getenv("EUREKA_URL")
	if eurekaUrl == "" && env != "dev" {
		log.Panic("EUREKA_URL is not set in .env file")
	}

	var h *server.Hertz
	if eurekaUrl != "" {
		r := eureka.NewEurekaRegistry([]string{eurekaUrl}, 40*time.Second)
		h = server.Default(
			server.WithHostPorts(addr),
			server.WithRegistry(r, &registry.Info{
				ServiceName: "user_service",
				Addr:        utils.NewNetAddr("tcp", addr),
				Weight:      10,
				Tags:        nil,
			}))
	} else {
		h = server.Default(
			server.WithHostPorts(addr))
	}

	register(h)
	h.Spin()
}
